package com.uchengwang.ui.utils;

import android.Manifest;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.uchengwang.R;
import com.uchengwang.functions.http.config.BaseConfig;
import com.uchengwang.functions.http.config.UserConfig;
import com.uchengwang.functions.http.entity.MapRequest;
import com.uchengwang.functions.http.listener.HttpCallBack;
import com.uchengwang.functions.http.listener.OnResultListener;
import com.uchengwang.functions.http.manager.HttpManager;
import com.uchengwang.ui.UChengApplication;
import com.uchengwang.ui.cm_ui.cycle.ui.LoadCycleWebHtmlActivity;
import com.uchengwang.ui.cm_ui.login.bean.UserBean;
import com.uchengwang.ui.cm_ui.ucity.listener.RxBusResultSubscriber;
import com.uchengwang.ui.cm_ui.ucity.ui.ImagePagerActivity;
import com.uchengwang.ui.cm_ui.ucity.ui.SwitchSchoolActivity;
import com.uchengwang.ui.cm_ui.umsg.bean.SchoolClubBean;
import com.uchengwang.ui.cm_ui.umsg.bean.WantChatBean;
import com.uchengwang.ui.cm_ui.umsg.ui.WantChatActivity;
import com.uchengwang.ui.listener.PermissionsListener;
import com.yalantis.ucrop.model.AspectRatio;
import com.zhy.autolayout.AutoLayoutActivity;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import cn.finalteam.rxgalleryfinal.RxGalleryFinal;
import cn.finalteam.rxgalleryfinal.RxGalleryFinalApi;
import cn.finalteam.rxgalleryfinal.bean.MediaBean;
import cn.finalteam.rxgalleryfinal.imageloader.ImageLoaderType;
import cn.finalteam.rxgalleryfinal.rxbus.RxBusResultDisposable;
import cn.finalteam.rxgalleryfinal.rxbus.event.ImageMultipleResultEvent;
import cn.finalteam.rxgalleryfinal.rxbus.event.ImageRadioResultEvent;
import cn.finalteam.rxgalleryfinal.ui.RxGalleryListener;
import cn.finalteam.rxgalleryfinal.ui.base.IMultiImageCheckedListener;
import cn.finalteam.rxgalleryfinal.ui.base.IRadioImageCheckedListener;
import cn.finalteam.rxgalleryfinal.utils.Logger;
import cn.jpush.android.api.JPushInterface;
import io.rong.imkit.RongIM;
import io.rong.imlib.model.Conversation;
import me.shaohui.advancedluban.Luban;
import me.shaohui.advancedluban.OnCompressListener;
import me.shaohui.advancedluban.OnMultiCompressListener;

/**
 * Created by U城网 on 2017/3/3.
 */

public class UCommonUtil {
    private static UCommonUtil util;
    //压缩图片后的
//    public final static String DEFAULT_SAVE_IMAGE_PATH =
//            Environment.getExternalStorageDirectory() + File.separator + "luban" +
//                    File.separator + "Images" + File.separator;

    private UCommonUtil() {
    }

    public static UCommonUtil getUtil() {
        if (util == null) {
            util = new UCommonUtil();
        }
        return util;
    }

    /**
     * 是否登录
     * */
    public boolean isLogin(){
        if ((UChengApplication.uid <= 0 && UChengApplication.clubId <=0) || TextUtils.isEmpty(UChengApplication.TOKEN)){
            return false;
        }
        return true;
    }

    /**
     *是否需要登录/认证 未登录需要跳转登录界面 未认证跳转认证界面
     * @param isNeedAuthen 是否需要判断认证与否 true需要判断是否认证
     * */
    public boolean isNeedLogin(Activity activity, boolean isNeedAuthen){
        if (!isLogin()){
            DialogUtils.getUtils().showLogin(activity);
            return true;
        } else if (isNeedAuthen && !UChengApplication.isAuthen ){
//            Intent intent = new Intent(activity, AuthenActivity.class);
            Intent intent = new Intent(activity, SwitchSchoolActivity.class);
            intent.putExtra(BaseConfig.TYPE, 4);
            intent.putExtra(BaseConfig.PUB_TYPE, 0);
            activity.startActivity(intent);
            return true;
        }
        return false;
    }

    /**
     * @param isAgainOpen true重新打开界面  false返回当前界面
     * */
    public boolean openLogin(Activity activity, boolean isAgainOpen){
        if (!isLogin()){
            DialogUtils.getUtils().showLogin(activity, isAgainOpen);
            return true;
        }
        return false;
    }

    public boolean isNeedToLogin(Activity activity, boolean isNeedAuthen){
        if (isNeedLogin(activity, isNeedAuthen)){
            return true;
        }
//        else if (UChengApplication.userRole == BaseConfig.CLUB_ROLE || UChengApplication.userRole == BaseConfig.UNI_ROLE){
//            return true;//社团和uni不能点击评论
//        }
        return false;
    }

    /**
     * 判断评论等是否可以显示
     * true显示  false不显示
     * @param id 发布人ID
     * */
    public boolean bottomIsShow(long id ){
//        if (UChengApplication.userRole != BaseConfig.CLUB_ROLE && UChengApplication.userRole != BaseConfig.UNI_ROLE){
//            //个人
////            if (isLogin() &&(id >0 && id == getId())){
////                //自己不显示
////                return false;
////            }
//            return true;
//        }
//        return false;
        if (UChengApplication.userRole >0){
            return true;
        }
        return false;
    }

    /**
     * 获取当前ID
     * */
    public long getId(){
        if (UChengApplication.userRole == 1){//个人
            return UChengApplication.uid;

        }else if (UChengApplication.userRole ==2){//社团
            return UChengApplication.clubId;

        }else if (UChengApplication.userRole ==3 || UChengApplication.userRole == BaseConfig.EDITOR_ROLE || UChengApplication.userRole == BaseConfig.ZONG_ROLE){//uni
            return UChengApplication.uid;
        }else {
            return 0;
        }
    }

    /**
     * 判断自己是否是几种Uni身份
     * */
    public boolean isUni(){
        if (UChengApplication.userRole ==BaseConfig.UNI_ROLE || UChengApplication.userRole == BaseConfig.EDITOR_ROLE ||
                UChengApplication.userRole ==BaseConfig.ZONG_ROLE){
            return true;
        }
        return false;
    }

    /**
     * 判断一个用户身份是不是Uni身份
     * */
    public boolean isUni(int userRole){
        if (userRole ==BaseConfig.UNI_ROLE || userRole == BaseConfig.EDITOR_ROLE || userRole ==BaseConfig.ZONG_ROLE){
            return true;
        }
        return false;
    }

    /**
     * 根据测试环境的不同 获取不同的oss拼接地址
     * @param type 1头像  2享说 3U城内容,社团纳新,社团/校吧内的贴子内的图片;
     * */
    public String getOssImageUrl (int type){
        String url = "";
        switch (type){
            case 2:
                url = "http://ucw-share.oss-cn-shanghai.aliyuncs.com/";
                break;
            case 3:
                url = "http://ucw-publish.oss-cn-shanghai.aliyuncs.com/";
                break;
        }
        return url;
    }

    /**
     * 跳转到他人的信息界面
     * @param uid 被查看人的ID
     * */
    public void toUserActivity(final Activity context, long uid){
        if (!NetwotkUtil.isConnectInternet()){
            showToast(context, "请检查网络");
            return;
        }

        LoadingUtils.getUtils().loading(context);
        MapRequest map = new MapRequest();
        map.put(BaseConfig.ID, uid);

        HttpManager.newInstance(context).query(UserConfig.ChangeInfo.method_check, UserConfig.ChangeInfo.URL, map, new HttpCallBack() {
            @Override
            public void onError(int status, String msg) {
                LoadingUtils.getUtils().hide();
                UCommonUtil.getUtil().showToast(context, "获取失败");
            }

            @Override
            public void onResp(int status, String msg, String data) {
                LoadingUtils.getUtils().hide();
                if (status != 0){
                    UCommonUtil.getUtil().showToast(context, msg);
                    return;
                }
                if (!TextUtils.isEmpty(data)){
                    UserBean userBean = JsonUtils.getManager().stringToBean(data, UserBean.class);
                    if (userBean != null){
                        Intent in = null;
                        int role = userBean.getUserRole();
                        switch (role){
                            case BaseConfig.STUDENT_ROLE:
                            case BaseConfig.EDITOR_ROLE:
//                                in = new Intent(context, UserInfoActivity.class);
//                                in = new Intent(context, MainPageActivity.class);
//                                in.putExtra(BaseConfig.ID, userBean.getId());
//                                in.putExtra(BaseConfig.BEAN, userBean);

                                in = new Intent(context, LoadCycleWebHtmlActivity.class);
                                in.putExtra(BaseConfig.URL, BaseConfig.BaseWebURL + "/user/"+userBean.getId());
                                break;
                            case BaseConfig.CLUB_ROLE:
                            case BaseConfig.UNI_ROLE:
                            case BaseConfig.ZONG_ROLE:
                                SchoolClubBean schoolClubBean = null;
                                if (role ==BaseConfig.UNI_ROLE || role == BaseConfig.ZONG_ROLE){
                                    schoolClubBean = new SchoolClubBean();
                                    schoolClubBean.setFollow(userBean.isFollow());
                                    schoolClubBean.setOrgName(userBean.getNickName());
                                    schoolClubBean.setUid(userBean.getId());
                                    schoolClubBean.setUniName(userBean.getUniName());
                                    schoolClubBean.setOrgSign(userBean.getUserSign());
                                    schoolClubBean.setOrgDescription(userBean.getDec());
                                    schoolClubBean.setLogoImg(userBean.getUserAvatar());
                                }else {
                                    schoolClubBean = userBean.getOrgView();
                                    if (schoolClubBean ==null){
                                        return;
                                    }
                                    schoolClubBean.setFollow(userBean.isFollow());
                                    if (TextUtils.isEmpty(schoolClubBean.getLogoImg())){
                                        schoolClubBean.setLogoImg(userBean.getUserAvatar());
                                    }
                                }

//                                in = new Intent(context, ClubDetailActivity.class);
//                                in.putExtra(BaseConfig.CLUB_ID, userBean.getId());
//                                in.putExtra(BaseConfig.USER_ROLE, role);
//                                in.putExtra(BaseConfig.BEAN, schoolClubBean);

//                                in = new Intent(context, MainPageActivity.class);
//                                in.putExtra(BaseConfig.ID, userBean.getId());
//                                in.putExtra(BaseConfig.BEAN, userBean);

                                in = new Intent(context, LoadCycleWebHtmlActivity.class);
                                in.putExtra(BaseConfig.URL, BaseConfig.BaseWebURL + "/user/"+userBean.getId());
                                break;

                        }
                        if (in != null){
                            context.startActivity(in);

                        }

                    }
                }else {
                    UCommonUtil.getUtil().showToast(context, msg);
                }
            }
        });
    }

    /**
     * 跳转到聊天界面
     * */
    public void toChatActiviy(Context context, long id, Conversation.ConversationType chatType, String nickName){
        toChatActiviy(context, String.valueOf(id), chatType, nickName);
    }
    public void toChatActiviy(Context context, String id, Conversation.ConversationType chatType, String nickName){
        if (isNeedLogin((Activity) context, false)){
            return;
        }
        RongIM.getInstance().startConversation(context, chatType, id, nickName);
    }

    /**
     * 通过uri打开界面
     * */
    public void toActivity(Context context, String uri){
        Intent intent = new Intent("android.intent.action.VIEW");
        intent.setData(Uri.parse(uri));
        context.startActivity(intent);
    }

    /**
     * 跳转到享聊界面
     * */
    public void toWantChat(Context context, WantChatBean bean, Conversation.ConversationType type){
        Intent intent = new Intent(context, WantChatActivity.class);
        intent.putExtra(BaseConfig.BEAN, bean);
        intent.putExtra(BaseConfig.TYPE, type);
        context.startActivity(intent);
    }

    /**
     * 返回当前的界面是否处于前台显示状态
     *
     * @param className
     * @return
     */
    private boolean isTopActivity(Context context, String className) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
        ComponentName componentInfo = taskInfo.get(0).topActivity;
        String cName = componentInfo.getClassName();
        if (className.equals(cName)) {
            return true;
        }
        return false;
    }

    /**
     * 单选裁剪
     * */
    public void openAndCrop(final Context context, final HttpCallBack callBack) {
        PermissionUtils.getUtils().checkStorage((Activity) context, new PermissionsListener() {
            @Override
            public void onSuccess() {
                RxGalleryFinalApi.getInstance((Activity) context)
                        .onCrop(true)//是否裁剪
                        .openGalleryRadioImgDefault(
                                new RxBusResultDisposable<ImageRadioResultEvent>() {
                                    @Override
                                    protected void onEvent(ImageRadioResultEvent imageRadioResultEvent) throws Exception {
                                        //图片自动会存储到下面，裁剪会自动生成路径；也可以手动设置裁剪的路径；
                                        RxGalleryFinalApi.setImgSaveRxCropDir(new File(PathUtils.UCW_CROP_IMAGE));


                                    }
                                })
                        .onCropImageResult(new IRadioImageCheckedListener() {
                            @Override
                            public void cropAfter(Object t) {
                                Logger.i("裁剪完成");
                                callBack.onResp(0, "", ((File)t).getAbsolutePath());
                            }

                            @Override
                            public boolean isActivityFinish() {
                                Logger.i("返回false不关闭，返回true则为关闭");
                                return true;
                            }
                        });
            }

            @Override
            public void onFailed() {
                showToast(context, "授权取消");
            }
        });
    }


    /**
     * 单选裁剪 指定参数
     * */
    public void openAndCrop(final Context context, final OnResultListener listener) {
        PermissionUtils.getUtils().checkStorage((Activity) context, new PermissionsListener() {
            @Override
            public void onSuccess() {
                RxGalleryFinal.with(context)
                        .image()
                        .radio()
                        .cropMaxResultSize(800, 800)//设置最大的宽度和高度
                        .cropAspectRatioOptions(0, new AspectRatio("1:1", 30, 30))//30 30指定裁剪框的比例 按比例算的
                        .crop()
                        .imageLoader(ImageLoaderType.GLIDE)
                        .subscribe(new RxBusResultDisposable<ImageRadioResultEvent>() {
                            @Override
                            protected void onEvent(ImageRadioResultEvent imageRadioResultEvent) throws Exception {
                            }
                        })
                        .openGallery();

                RxGalleryFinalApi.getInstance((Activity) context).onCropImageResult(new IRadioImageCheckedListener() {
                    @Override
                    public void cropAfter(Object t) {
                        Logger.i("裁剪完成");
                        Log.d("jjf", "裁剪成功=="+((File)t).getAbsolutePath());
//                        showToast(context, ((File)t).getAbsolutePath());
                        listener.onResult(0, null, 0, ((File)t).getAbsolutePath());
                    }

                    @Override
                    public boolean isActivityFinish() {
                        Logger.i("返回false不关闭，返回true则为关闭");
                        return true;
                    }
                });
            }

            @Override
            public void onFailed() {
                showToast(context, "授权取消");
            }
        });


    }


    /**
     * RxGalleryFinal单选图片打开
     * */
    public void openGallerySingle(final Context context, final RxBusResultSubscriber<ImageRadioResultEvent> subscriber) {
        PermissionUtils.getUtils().checkStorage((Activity) context, new PermissionsListener() {
            @Override
            public void onSuccess() {
                RxGalleryFinal.with(context)
                        .image().cropropCompressionQuality(60)
                        .radio()
                        .imageLoader(ImageLoaderType.GLIDE)
                        .subscribe(new RxBusResultDisposable<ImageRadioResultEvent>() {
                            @Override
                            protected void onEvent(ImageRadioResultEvent baseResultEvent) throws Exception {
                                subscriber.onEvent(baseResultEvent);
                            }
                        }).openGallery();
            }

            @Override
            public void onFailed() {
                showToast(context, "授权取消");
            }
        });



    }

    /**
     * RxGalleryFinal多选图片打开
     * @param maxSize 最多选择几张照片
     * @param beanList 选中的图片
     * @param subscriber 选择完成的回调监听器
     * */
    public void openGalleryMultiple(final Context context, final int maxSize, final RxBusResultSubscriber<ImageMultipleResultEvent> subscriber,
                                    final List<MediaBean> beanList,
                                    final IMultiImageCheckedListener checkedListener) {
        PermissionUtils.getUtils().checkStorage((Activity) context, new PermissionsListener() {
            @Override
            public void onSuccess() {
                RxGalleryFinal galleryFinal = RxGalleryFinal
                        .with(context.getApplicationContext())
                        .image().cropropCompressionQuality(60)
                        .multiple()
                        .maxSize(maxSize)
                        .imageLoader(ImageLoaderType.GLIDE)
                        .subscribe(new RxBusResultDisposable<ImageMultipleResultEvent>() {
                            @Override
                            protected void onEvent(ImageMultipleResultEvent baseResultEvent) throws Exception {
                                subscriber.onEvent(baseResultEvent);
                            }
                        });
                if (beanList != null && beanList.size() > 0) {
                    galleryFinal.selected(beanList);
                }
                galleryFinal.openGallery();

                if (checkedListener == null) {
                    //得到图片多选的事件
                    RxGalleryListener.getInstance().setMultiImageCheckedListener(new IMultiImageCheckedListener() {
                        @Override
                        public void selectedImg(Object t, boolean isChecked) {
                            //这个主要点击或者按到就会触发，所以不建议在这里进行Toast
                    /*  Toast.makeText(getBaseContext(),"->"+isChecked,Toast.LENGTH_SHORT).show();*/
                        }

                        @Override
                        public void selectedImgMax(Object t, boolean isChecked, int maxSize) {
                            Toast.makeText(context.getApplicationContext(), "你最多只能选择" + maxSize + "张图片", Toast.LENGTH_SHORT).show();
                        }
                    });
                } else {
                    RxGalleryListener.getInstance().setMultiImageCheckedListener(checkedListener);
                }
            }

            @Override
            public void onFailed() {
                showToast(context, "授权取消");
            }
        });


    }

    /**
     * RxGalleryFinal视频打开
     * */
    public void openVideoRadio(final Context context, final IMultiImageCheckedListener checkedListener) {
        PermissionUtils.getUtils().checkStorage((Activity) context, new PermissionsListener() {
            @Override
            public void onSuccess() {
                RxGalleryFinalApi
                        .getInstance((Activity) context)
                        .setType(RxGalleryFinalApi.SelectRXType.TYPE_VIDEO, RxGalleryFinalApi.SelectRXType.TYPE_SELECT_RADIO)
                        .setVDRadioResultEvent(new RxBusResultDisposable<ImageRadioResultEvent>() {
                            @Override
                            protected void onEvent(ImageRadioResultEvent imageRadioResultEvent) throws Exception {
                                Toast.makeText(context, imageRadioResultEvent.getResult().getOriginalPath(), Toast.LENGTH_SHORT).show();
                            }
                        })
                        .open();
            }

            @Override
            public void onFailed() {
                showToast(context, "授权取消");
            }
        });


    }


    /**
     * Toast多次弹出的问题
     * */
    private Toast toast;

    public void showToast(final Context context, final String text) {
        if (toast == null && context != null) {
            toast = Toast.makeText(context.getApplicationContext(), text, Toast.LENGTH_SHORT);
        } else {
            toast.setText(text);
        }
        toast.show();
    }



    /**
     * 压缩图片 单张 也有RxJava调用方式
     * @param path
     * @param listener
     * luban第二个参数传的是图片压缩后的存储地址
     * @param size 压缩后的容量KB
     * */
    public void compressImageAlone(Context context,int size,  String path, OnCompressListener listener) {
        File file = new File(path);
        if (null == file || !file.exists()) {
            showToast(context, "图片地址不存在");
            return;
        }

        Luban.compress(file, getPhotoCache(context)).setMaxSize(size)
                .putGear(Luban.CUSTOM_GEAR).launch(listener);

    }
    /**
     * 压缩图片 单张 也有RxJava调用方式
     * @param file
     * @param listener
     * luban第二个参数传的是图片压缩后的存储地址
     * @param size 压缩后的容量KB
     * */
    public void compressImageAlone(Context context,int size,  File file, OnCompressListener listener) {
        if (null == file || !file.exists()) {
            showToast(context, "图片地址不存在");
            return;
        }
        Luban.compress(file, getPhotoCache(context)).setMaxSize(size)
                .putGear(Luban.CUSTOM_GEAR).launch(listener);

    }

    /**
     * 压缩图片 多张 也有RxJava调用方式
     * @param stringList 需要压缩的图片集合
     * @param listener
     * @param size 压缩后的容量KB
     * luban第二个参数传的是图片压缩后的存储地址
     * */
    public void compressImageMulti(Context context,int size, List<String> stringList, OnMultiCompressListener listener) {

        List<File> list = new ArrayList<>();
        for (String s : stringList){
            File file = new File(s);
            if (null == file || !file.exists()) {
                continue;
            }
            list.add(file);
            try {
                Log.d("yasuo", "压缩前="+s +"==file=="+file.getAbsolutePath());
                Log.d("yasuo", "压缩前="+getFileSize(file));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        Luban.compress(list, getPhotoCache(context)).setMaxSize(size)
                .putGear(Luban.CUSTOM_GEAR).launch(listener);

    }

    /**
     * 获取指定文件大小
     * @param file
     * @return
     * @throws Exception 　　
     */
    public long getFileSize(File file) throws Exception {
        long size = 0;
        if (file.exists()) {
            FileInputStream fis = null;
            fis = new FileInputStream(file);
            size = fis.available();
        } else {
            Log.e("获取文件大小", "文件不存在!");
        }
        return size;
    }

    private File getPhotoCache(Context context) {
        File cacheDir = context.getExternalCacheDir();
        if (cacheDir != null) {
            File result = new File(cacheDir, "luban_disk_cache");
            if (!result.mkdirs() && (!result.exists() || !result.isDirectory())) {
                // File wasn't able to create a directory, or the result exists but not a directory
                return null;
            }
            return result;
        }
        if (Log.isLoggable("jjf", Log.ERROR)) {
            Log.e("jjf", "default disk cache dir is null");
        }
        return null;
    }


    /**
     * 依次为打开软键盘  隐藏软键盘 判断软键盘是否打开
     * */
    public void showSoftInput(Context context, View view) {
        InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
        //imm.showSoftInput(view, InputMethodManager.SHOW_FORCED);
    }

    public void hideSoftInput(Context context, View view) {
        InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0); //强制隐藏键盘
    }

    public boolean isShowSoftInput(Context context) {
        InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        //获取状态信息
        return imm.isActive();//true 打开
    }


    //调取系统拨号功能 [跳转到拨号界面]
    public void callPhone(Context context, String phone) {
        if (UCommonUtil.getUtil().isNeedLogin((Activity) context, false)){
            return;
        }
        Intent intent = new Intent(Intent.ACTION_DIAL);
        Uri data = Uri.parse("tel:" + phone);
        intent.setData(data);
        context.startActivity(intent);
    }

    /**
     * 设置添加屏幕的背景透明度
     *
     * @param bgAlpha
     */
    public void backgroundAlpha(Context context, float bgAlpha) {
        try {
            WindowManager.LayoutParams lp = ((AutoLayoutActivity) context).getWindow().getAttributes();
            lp.alpha = bgAlpha;
            if (bgAlpha == 1) {
                ((AutoLayoutActivity) context).getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
                //不移除该Flag的话,在有视频的页面上的视频会出现黑屏的bug
            } else {
                ((AutoLayoutActivity) context).getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
                //此行代码主要是解决在华为手机上半透明效果无效的bug
            }
            ((AutoLayoutActivity) context).getWindow().setAttributes(lp);
        } catch (Exception e) {
            new IllegalAccessException("请检查是否继承AutoLayoutActivity");
        }
    }


    //版本信息
    public  String getVersionName(Context context) {
        if (getPackageInfo(context) != null) {
            return getPackageInfo(context).versionName;
        }
        return null;
    }

    /**
     * 获取app信息
     *
     * @param context
     * @return
     */
    public  PackageInfo getPackageInfo(Context context) {
        PackageInfo packageInfo = null;
        try {
            packageInfo = context.getPackageManager()
                    .getPackageInfo(context.getPackageName(),
                            PackageManager.GET_CONFIGURATIONS);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return null;
        }
        return packageInfo;
    }

    /**
     * 获取设备ID
     * @param isOnlyDeviceId 只获取设备ID
     * */
    public String getDeviceInfo(Context context, boolean isOnlyDeviceId) {
        try {
            org.json.JSONObject json = new org.json.JSONObject();
            android.telephony.TelephonyManager tm = (android.telephony.TelephonyManager) context
                    .getSystemService(Context.TELEPHONY_SERVICE);
            String device_id = null;
            if (checkPermission(context, Manifest.permission.READ_PHONE_STATE)) {
                device_id = tm.getDeviceId();
            }
            String mac = null;
            FileReader fstream = null;
            try {
                fstream = new FileReader("/sys/class/net/wlan0/address");
            } catch (FileNotFoundException e) {
                fstream = new FileReader("/sys/class/net/eth0/address");
            }
            BufferedReader in = null;
            if (fstream != null) {
                try {
                    in = new BufferedReader(fstream, 1024);
                    mac = in.readLine();
                } catch (IOException e) {
                } finally {
                    if (fstream != null) {
                        try {
                            fstream.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (in != null) {
                        try {
                            in.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
            if (TextUtils.isEmpty(device_id)) {
                device_id = mac;
            }
            json.put("mac", mac);
            if (TextUtils.isEmpty(device_id)) {
                device_id = android.provider.Settings.Secure.getString(context.getContentResolver(), android.provider.Settings.Secure.ANDROID_ID);
            }
            json.put("device_id", device_id);
            if (isOnlyDeviceId){
                return device_id;
            }
            return json.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 根据Pid获取当前进程的名字，一般就是当前app的包名
     *
     * @param pid 进程的id
     * @return 返回进程的名字
     */
    public String getAppName(int pid, Context context) {
        String processName = null;
        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List list = activityManager.getRunningAppProcesses();
        Iterator i = list.iterator();
        while (i.hasNext()) {
            ActivityManager.RunningAppProcessInfo info = (ActivityManager.RunningAppProcessInfo) (i.next());
            try {
                if (info.pid == pid) {
                    // 根据进程的信息获取当前进程的名字
                    processName = info.processName;
                    // 返回当前进程名
                    return processName;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        // 没有匹配的项，返回为null
        return null;
    }

    private boolean checkPermission(Context context, String permission) {
        boolean result = false;
        if (Build.VERSION.SDK_INT >= 23) {
            try {
                Class<?> clazz = Class.forName("android.content.Context");
                Method method = clazz.getMethod("checkSelfPermission", String.class);
                int rest = (Integer) method.invoke(context, permission);
                if (rest == PackageManager.PERMISSION_GRANTED) {
                    result = true;
                } else {
                    result = false;
                }
            } catch (Exception e) {
                result = false;
            }
        } else {
            PackageManager pm = context.getPackageManager();
            if (pm.checkPermission(permission, context.getPackageName()) == PackageManager.PERMISSION_GRANTED) {
                result = true;
            }
        }
        return result;
    }

    // 校验极光Tag Alias 只能是数字,英文字母和中文
    public static boolean isValidTagAndAlias(String s) {
        Pattern p = Pattern.compile("^[\u4E00-\u9FA50-9a-zA-Z_!@#$&*+=.|]+$");
        Matcher m = p.matcher(s);
        return m.matches();
    }


    // 取得版本号
    public String GetVersion(Context context) {
        try {
            PackageInfo manager = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
            return manager.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            return "Unknown";
        }
    }

    public String getImei(Context context, String imei) {
        try {
            TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
            imei = telephonyManager.getDeviceId();
        } catch (Exception e) {
            Log.d("jjf", e.getMessage());
        }
        return imei;
    }

    public String getDeviceId(Context context) {
        String deviceId = JPushInterface.getUdid(context.getApplicationContext());
        return deviceId;
    }

    /**
     * 转为json时, 将一个文字中的英文双引号该为单引号
     * */
    public String replaceQuotes(String data){
        if (!TextUtils.isEmpty(data)){
            data.replaceAll("\"", "\'");
        }
        return data;
    }

    /**
     * 获取图片地址集合里的一张作为cover
     * @param imgs 图片地址集合
     * @param isAdd 是否需要拼接
     * @param type 图片类型
     * */
    public String getCover(String imgs, boolean isAdd, int type){
        if (!TextUtils.isEmpty(imgs)){
             List<String> images = Arrays.asList(imgs.split(";"));
            String image = images.get(0);
            if (isAdd){
                String url = getOssImageUrl(type) + image;
                return url;
            }
            return image;
        }
        return null;
    }



    /**
     * 跳转到图片查看页
     * */
    public void startImagePagerActivity(Context context, List<String> imgUrls, int position, boolean isLocal) {
        Intent intent = new Intent(context, ImagePagerActivity.class);
        intent.putStringArrayListExtra(BaseConfig.INTENT_IMGURLS, new ArrayList<>(imgUrls));
        intent.putExtra(BaseConfig.INTENT_POSITION, position);
        intent.putExtra(BaseConfig.IS_LOCAL, isLocal);
        context.startActivity(intent);
    }

    public void startImagePagerActivity(Context context, int pubType, List<String> imgUrls, int position, boolean isLocal) {
        Intent intent = new Intent(context, ImagePagerActivity.class);
        intent.putStringArrayListExtra(BaseConfig.INTENT_IMGURLS, new ArrayList<>(imgUrls));
        intent.putExtra(BaseConfig.INTENT_POSITION, position);
        intent.putExtra(BaseConfig.PUB_TYPE, pubType);
        intent.putExtra(BaseConfig.IS_LOCAL, isLocal);
        context.startActivity(intent);
    }

    /**
     * 获取当前进程的名字
     * */
    public String getCurProcessName(Context applicationContext) {
        ActivityManager activityManager = (ActivityManager) applicationContext.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> runningApps = activityManager.getRunningAppProcesses();
        if (runningApps == null) {
            return null;
        }
        int pid = android.os.Process.myPid();
        for (ActivityManager.RunningAppProcessInfo procInfo : runningApps) {
            if (procInfo.pid == pid) {
                return procInfo.processName;
            }
        }
        return null;
    }

}
